/**
 * @Title:  GroupPhotoActivity.java 
 * @Copyright:  XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
 * @Description:  TODO<请描述此文件是做什么的> 
 * @author:  MeiYi 
 * @data:  2016-4-26 下午5:13:20 
 * @version:  V1.0 
 */

package artid.com.arttogoa.keeponrecord;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import artid.com.arttogoa.HomeActivity;
import artid.com.arttogoa.R;
import artid.com.arttogoa.adapter.MicFragmentAdapter;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.FilesBean;
import artid.com.arttogoa.parser.MicMapBean;
import artid.com.arttogoa.task.CallbackSky;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.CameraUtils;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.view.SubViewPager;

/**
 * TODO<请描述这个类是干什么的>
 * 
 * @author 熊彬
 * @data: 2016-4-26 下午5:13:20
 * @version: V1.0
 */
public class MicroscopicMapBrowseActivity extends FragmentActivity implements
		OnClickListener {
	private TextView title, right, prompt, index;
	private AlertDialog alertDialog;
	private ArrayList<MicMapBean> dataB;
	private EditText info;
	private ImageView micImg;
	private ImageView back;
	private int ind;
	/** 上传模式 */
	private String updataType;
	/** 当前点描述 */
	private String poiString;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_microscopic_map_see);
		title = (TextView) findViewById(R.id.title_text);
		right = (TextView) findViewById(R.id.title_fb);
		prompt = (TextView) findViewById(R.id.tv_prompt);
		index = (TextView) findViewById(R.id.tv_mic_index);
		info = (EditText) findViewById(R.id.tv_info);
		info.addTextChangedListener(textWatcher);
		back = (ImageView) findViewById(R.id.back_btn);
		back.setOnClickListener(this);
		title.setText("微观图");
		right.setOnClickListener(this);
		System.out.println(4);
		dataB = (ArrayList<MicMapBean>) getIntent().getExtras()
				.getSerializable("data");
		ind = getIntent().getIntExtra("index", 0);
		/** 初始化备案模式 **/
		updataType = MySharedPreferences.getMySharedPreferences(
				MicroscopicMapBrowseActivity.this).getValue(Cache.ART_TYPE, "");
		/** 初始化标题标志 **/
		Drawable drawable = null;
		if (updataType.equals(ArtRecordActivity._PHONE)) {
			poiString = "局部特征图";
			drawable = getResources().getDrawable(R.drawable.a_ico_iphone);
		} else if (updataType.equals(ArtRecordActivity._FILING)) {
			poiString = "微观特征点";
			drawable = getResources().getDrawable(R.drawable.a_ico_shebei);
		}
		title.setText(poiString);
		info.setHint(poiString + "及描述信息");
		// / 这一步必须要做,否则不会显示.
		drawable.setBounds(0, 0, drawable.getMinimumWidth(),
				drawable.getMinimumHeight());
		title.setCompoundDrawablePadding(20);
		title.setCompoundDrawables(drawable, null, null, null);
		initViewPager();
	}

	private SubViewPager mViewPager;
	private ArrayList<View> pageview;
	// 主适配器
	private MicFragmentAdapter mFragmentAdapter;
	int dexId;

	/**
	 * 
	 */
	private void initViewPager() {
		// TODO Auto-generated method stub
		mViewPager = (SubViewPager) findViewById(R.id.viewPager);
		mFragmentAdapter = new MicFragmentAdapter(getSupportFragmentManager(),
				new CallbackSky() {
					@Override
					public void callBack(final int index) {
						// TODO Auto-generated method stub
						dexId = index;
						
//						Intent intent = new Intent(
//								MicroscopicMapBrowseActivity.this,
//								HomeActivity.class);
//						intent.putExtra("type", "micSD");
//						startActivityForResult(intent, 2);
						if (updataType.equals(ArtRecordActivity._FILING)) {
							Intent intent = new Intent(MicroscopicMapBrowseActivity.this,
									HomeActivity.class);
							intent.putExtra("type", Cache.T_DIV);
							startActivityForResult(intent, 2);
						} else if (updataType.equals(ArtRecordActivity._PHONE)) {

							// alertDialog.dismiss();
							alertDialog = AlertUtils.initFilingPhotoAlertDialog(
									MicroscopicMapBrowseActivity.this,
									MicroscopicMapBrowseActivity.this.getWindowManager()
											.getDefaultDisplay().getWidth(),
									new OnClickListener() {

										@Override
										public void onClick(View view) {
											// TODO Auto-generated method stub
											switch (view.getId()) { 
											case R.id.tv_phone:
												CameraUtils
														.openCameraImage(MicroscopicMapBrowseActivity.this);
												alertDialog.dismiss();
												break;
											case R.id.tv_choice:
												Intent intent = new Intent(
														MicroscopicMapBrowseActivity.this,
														HomeActivity.class);
												intent.putExtra("type", Cache.T_PH);
												intent.putExtra("index", 1);
												intent.putExtra("pictureLimit",
														dataB.get(index).isArtMictype()?"2":"1");
												startActivityForResult(intent, 2);
												alertDialog.dismiss(); 
												break;
											case R.id.tv_diver:
												Intent intent2 = new Intent(
														MicroscopicMapBrowseActivity.this,
														HomeActivity.class);
												intent2.putExtra("type", Cache.T_PH);
												intent2.putExtra("index", 0);
												intent2.putExtra("pictureLimit",
														dataB.get(index).isArtMictype()?"2":"1");
												startActivityForResult(intent2, 2);
												alertDialog.dismiss();
												break;
											default:
												break;
											}
										}
									}, dataB.get(index).isArtMictype()?2:1);
						}
					}
				}, updataType);
		mFragmentAdapter.setData(dataB);
		mFragmentAdapter.notifyDataSetChanged();
		mViewPager.setAdapter(mFragmentAdapter);
		mViewPager.setOffscreenPageLimit(dataB.size() * 2);
		mViewPager.setOnPageChangeListener(mOnPageChangeListener);
		if (updataType.equals(ArtRecordActivity._PHONE)) {
			mViewPager.setCurrentItem(ind);
			prompt.setText("第" + (ind + 1) + "个" + poiString + "及描述信息");
			index.setText((ind + 1) + "/" + dataB.size());
		} else {
			mViewPager.setCurrentItem(ind * 2);
			prompt.setText("第" + (ind + 1) + "个点60倍" + poiString + "及描述信息");
			index.setText((ind * 2 + 1) + "/" + dataB.size() * 2);
		}
		info.setText(dataB.get(ind).getNewInfo());
	}

	private TextWatcher textWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			//
			System.out.println("-1-onTextChanged-->"
					+ info.getText().toString() + "<--");
			dataB.get(position).setNewInfo(info.getText().toString());
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			//
			System.out.println("-2-beforeTextChanged-->"
					+ info.getText().toString() + "<--");
			// dataB.get(position).setNewInfo(info.getText().toString());

		}

		@Override
		public void afterTextChanged(Editable s) {
			//
			System.out.println("-3-afterTextChanged-->"
					+ info.getText().toString() + "<--");

		}
	};
	private int position = 0;
	private int o = 0;
	private OnPageChangeListener mOnPageChangeListener = new OnPageChangeListener() {
		@Override
		public void onPageSelected(int pos) {
			o = pos;
			if (updataType.equals(ArtRecordActivity._PHONE)) {
				MicroscopicMapBrowseActivity.this.position = pos;
				System.out.println("positionSelect=" + pos);
				prompt.setText("第" + (position + 1) + "个" + poiString + "及描述信息");
				info.setText(dataB.get(position).getNewInfo());
				index.setText((pos + 1) + "/" + dataB.size());
			} else {
				MicroscopicMapBrowseActivity.this.position = pos / 2;
				System.out.println("positionSelect=" + pos);
				prompt.setText("第" + (position + 1) + "个点的"
						+ (pos % 2 == 1 ? "200倍" : "60倍") + poiString + "及描述信息");
				info.setText(dataB.get(position).getNewInfo());
				index.setText((pos + 1) + "/" + dataB.size() * 2);
			}

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageScrollStateChanged(int pos) {
			System.out.println("positionStateChanged=" + pos);
			// MicroscopicMapBrowseActivity.this.position = pos;
			// prompt.setText("第" + (position) + "个点的微观图及描述信息");
			// info.setText(dataB.get(position - 1).getInfo());
			// index.setText(position + "/" + dataB.size());
		}
	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.back_btn:
			System.out.println(dataB.toString());
			back();
			// Intent intent = new Intent(MicroscopicMapBrowseActivity.this,
			// MicroscopicMapSelectActivity.class);
			// Bundle b = new Bundle();
			// b.putSerializable("data", dataB);
			// intent.putExtras(b);
			// MicroscopicMapBrowseActivity.this.setResult(10, intent);
			// MicroscopicMapBrowseActivity.this.finish();
			break;

		default:
			break;
		}
	}

	private boolean empty = false;
	private boolean changed = false;
	private boolean finsh = false;

	/**
	 * 
	 * @Title: back
	 * @Description: TODO (返回时进行的判定)
	 * @param 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	private void back() {
		// TODO Auto-generated method stub
		for (int i = 0; i < dataB.size(); i++) {
			if (TextUtils.isEmpty(dataB.get(i).getNewInfo())) {
				empty = true;
				break;
			} else if (!dataB.get(i).getNewInfo()
					.equals(dataB.get(i).getInfo())) {
				changed = true;
				break;
			}
		}
		if (empty) {
			AlertUtils.initSubmitSumAlertDialog(
					MicroscopicMapBrowseActivity.this, "还有作品没有添加描述信息");
			return;
		} else if (changed) {
			AlertUtils.AlertTwoBtnDialog(MicroscopicMapBrowseActivity.this,
					"确定保存修改过的" + poiString + "及描述吗?", "确定", "取消",
					getWindowManager().getDefaultDisplay().getWidth(),
					backClick);
			return;
		}
		finish();
	}

	OnClickListener backClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.tv_ok:
				finsh = true;
				changedData();
				Intent intent = new Intent(MicroscopicMapBrowseActivity.this,
						MicroscopicMapSelectActivity.class);
				Bundle b = new Bundle();
				b.putSerializable("data", dataB);
				intent.putExtras(b);
				MicroscopicMapBrowseActivity.this.setResult(10, intent);
				MicroscopicMapBrowseActivity.this.finish();
				finish();
				break;
			case R.id.tv_no:
				finsh = false;
				AlertUtils.dismiss();
				finish();
				break;

			default:
				break;
			}
		}
	};

	private String imageUrl;

	private void changedData() {
		// TODO Auto-generated method stub
		for (int i = 0; i < dataB.size(); i++) {
			if (finsh) {
				dataB.get(i).setInfo(dataB.get(i).getNewInfo());
			}
		}
	}

	@SuppressLint("SdCardPath")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CameraUtils.GET_IMAGE_BY_CAMERA) {
			final Uri uri = CameraUtils.imageUriFromCamera;
			imageUrl = BitmapUtil.getRealFilePath(
					MicroscopicMapBrowseActivity.this, uri);
			// String sdStatus = Environment.getExternalStorageState();
			// if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			// Log.i("TestFile",
			// "SD card is not avaiable/writeable right now.");
			// return;
			// }
			// @SuppressWarnings("static-access")
			// String name = new DateFormat().format("yyyyMMdd_hhmmss",
			// Calendar.getInstance(Locale.CHINA))
			// + ".jpg";
			// // Toast.makeText(this, name, Toast.LENGTH_LONG).show();
			// Bundle bundle = data.getExtras();
			// Bitmap bitmap = (Bitmap) bundle.get("data");//
			// 获取相机返回的数据，并转换为Bitmap图片格式
			//
			// FileOutputStream b = null;
			// // ???????????????????????????????为什么不能直接保存在系统相册位置呢？？？？？？？？？？？？
			// File file = new File("/sdcard/myImage/");
			// file.mkdirs();// 创建文件夹
			// String fileName = "/sdcard/myImage/" + name;
			// imageUrl = fileName;
			// try {
			// b = new FileOutputStream(fileName);
			// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
			// } catch (FileNotFoundException e) {
			// e.printStackTrace();
			// } finally {
			// try {
			// b.flush();
			// b.close();
			// } catch (IOException e) {
			// e.printStackTrace();
			// }
			// }
		} else if (requestCode == 2 && resultCode == 3) {
			Bundle bundle = data.getExtras();
			FilesBean fb = (FilesBean) bundle.getSerializable("image");
			imageUrl = fb.getImgURL();
		} else if (requestCode == 2 && resultCode == 4) {
			Bundle bundle = data.getExtras();
			FilesBean fb = (FilesBean) bundle.getSerializable("image");
			System.out.println(fb.getThumbURL());
			imageUrl = fb.getThumbURL();
		}
		if (updataType.equals(ArtRecordActivity._PHONE)) {
			dataB.get(position).setImage(imageUrl);
		} else {
			if ((dexId) % 2 == 1) {
				dataB.get(position).setImage200(imageUrl);
			} else {
				dataB.get(position).setImage(imageUrl);
			}

		}

		changed = true;
		mFragmentAdapter.setData(dataB);
		mFragmentAdapter.notifyDataSetChanged();
		mViewPager.setCurrentItem(o);
	}

	/**
	 * 加载本地图片 http://bbs.3gstdy.com
	 * 
	 * @param url
	 * @return
	 */
	public Bitmap getLoacalBitmap(String url) {
		imageUrl = url;
		try {
			FileInputStream fis = new FileInputStream(url);
			Bitmap bitmap = BitmapFactory.decodeStream(fis);
			return bitmap;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}
}
